package bat.iog.hytool.nio.demo1;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NioServerMain {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);

    public static void main(String[] args) {
        NioServerMain nioServerMain = new NioServerMain();
        nioServerMain.startSocket(7809);
    }


    public void startSocket(int port) {
        try {
            //获取一个channel
            ServerSocketChannel channel = ServerSocketChannel.open();
            //配置是否阻塞
            channel.configureBlocking(false);
            //获取socket
            ServerSocket server = channel.socket();
            //绑定服务及端口
            server.bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
            //获取到选择器
            Selector selector = Selector.open();
            //注册到选择器用以接受连接
            channel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务端socket 已经启动");
            executorService.execute(new NioReadThread(selector));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


